from pickle import TUPLE
import re
from typing import Tuple
from sympy import Piecewise, det_quick, symbols, sympify
from sympy.abc import x, y
import sympy
# x = 0.6
# expr = "x>1:1,2<x<10:2,x>10:3"
def parser(expr,x):

    try:
        expr_list = re.split(',', expr)

        res_dict = dict()
        res_dict['expr'] = list()
        res_dict['res'] = list()

        for item in expr_list:
            str_expr = re.split(':', item)[0]
            str_res = re.split(':', item)[1]
            res_dict['expr'].append(str_expr)
            res_dict['res'].append(str_res)

        for i in range(0, len(res_dict['expr'])):
            if(re.search('>{1}', res_dict['expr'][i]) != None):
                y = re.split('>', res_dict['expr'][i])[1]
                y = float(y.replace(" ",""))
                if(x > y):
                    return res_dict['res'][i]

            elif(re.search('<{1}', res_dict['expr'][i]) != None\
                and re.search('<{1}.+<{1}', res_dict['expr'][i]) == None):
                y = re.split('<', res_dict['expr'][i])[1]
                print(i)
                y = y.replace("\n", "")
                y = float(y.replace(" ", ""))
                if(x < y):
                    return res_dict['res'][i]

            elif(re.search('>{1}.+>{1}', res_dict['expr'][i]) != None):
                print(res_dict['expr'][i])
                y1 = re.split('>', res_dict['expr'][i])[0]
                y2 = re.split('>', res_dict['expr'][i])[2]
                y1 = float(y1.replace(" ",""))
                y2 = float(y2.replace(" ",""))
                if( x < max(y1, y2) and x > min(y1, y2)):
                    return res_dict['res'][i]

            elif(re.search('<{1}.+<{1}', res_dict['expr'][i]) != None):
                print(res_dict['expr'][i])
                y1 = re.split('<', res_dict['expr'][i])[0]
                y2 = re.split('<', res_dict['expr'][i])[2]
                y1 = float(y1.replace(" ",""))
                y2 = float(y2.replace(" ",""))
                if( x < max(y1, y2) and x > min(y1, y2)):
                    return res_dict['res'][i]
            else:
                return None
    except Exception as ex:
        print("parse expr error:" + str(ex))

def maybe_piecewise(expr):
    if re.search(':{1}.*,{1}', expr) != None:
        return True
    else :
        return False

def test():
    expr = "(0, x < -1), (1, x >= 1), (100,True)"
    res = eval(expr)
    p = Piecewise(*res)
    dic = dict()
    dic['x'] = 0
    print(p.subs(dic))
    
# test()
